//
//  QXSplashAdView.m
//  iAccountBook
//
//  Created by 侯伟 on 2021/9/5.
//

#import "QXSplashAdView.h"
#import "QXAdvert.h"
#import "QXAdHandler.h"

@interface QXSplashAdView(){
    dispatch_source_t _timer;
    int _count;
}

@property (nonatomic, strong) UIImageView *adImageView;

@property (nonatomic, strong) UIButton *skipBtn;

@property (nonatomic, strong) QXAdvert* advert;

@end

static int const showtime = 6;

@implementation QXSplashAdView


- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {

        _count = showtime;
        
        [self setupViews];
    }
    return self;
}

- (void)setupViews{
    
    self.backgroundColor = [UIColor colorWithWhite:0.3 alpha:0.3];
    
    // 1.广告图片
    UIImageView *adImageView = [[UIImageView alloc] initWithFrame:self.bounds];
    adImageView.contentMode = UIViewContentModeScaleAspectFill;
    adImageView.clipsToBounds = YES;
    adImageView.userInteractionEnabled = YES;
    [self addSubview:adImageView];
    _adImageView = adImageView;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click:)];
    [adImageView addGestureRecognizer:tap];

    // 2.跳过按钮
    CGFloat btnW = 60;
    CGFloat btnH = 28;
    UIButton *skipBtn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetWidth([UIScreen mainScreen].bounds) - btnW - 24, btnH, btnW, btnH)];
    [skipBtn addTarget:self action:@selector(skip:) forControlEvents:UIControlEventTouchUpInside];
    [skipBtn setTitle:[NSString stringWithFormat:@"跳过(%d)", _count] forState:UIControlStateNormal];
    skipBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [skipBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    skipBtn.backgroundColor = [UIColor colorWithRed:38 /255.0 green:38 /255.0 blue:38 /255.0 alpha:0.6];
    skipBtn.layer.cornerRadius = 14;
    [self addSubview:skipBtn];
    _skipBtn = skipBtn;
}

#pragma mark  -- load

- (void)loadAdData{
    [[QXAdHandler shareHander] requestQXAdWithAdType:ADType_Splash block:^(QXAdvert * _Nullable ad) {
        if(!ad){
            if(self.delegate && [self.delegate respondsToSelector:@selector(QXSplashAdLoadFaild:)]){
                [self.delegate QXSplashAdLoadFaild:self];
            }
            return;
        }
        self.advert = ad;
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSURL* URL = [NSURL URLWithString:ad.image];
            NSData* imageData = [NSData dataWithContentsOfURL:URL];
            UIImage* image = [UIImage imageWithData:imageData];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                self.adImageView.image = image;
                if(image){
                    if(self.delegate && [self.delegate respondsToSelector:@selector(QXSplashAdDidLoaded:)]){
                        [self.delegate QXSplashAdDidLoaded:self];
                    }
                }else{
                    if(self.delegate && [self.delegate respondsToSelector:@selector(QXSplashAdDidLoaded:)]){
                        [self.delegate QXSplashAdLoadFaild:self];
                    }
                }
            });
        });
    }];
}

// GCD倒计时
- (void)startTimer{

    if(_timer){
        dispatch_resume(_timer);
        return;
    }
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    _timer = timer;
    
    dispatch_source_set_timer(timer,dispatch_walltime(NULL, 0),1.0 * NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(timer, ^{
        
        self->_count --;
        
        if(self->_count <= 0){ //倒计时结束，关闭
            dispatch_async(dispatch_get_main_queue(), ^{
                [self dismiss];
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.skipBtn setTitle:[NSString stringWithFormat:@"跳过(%d)",self->_count] forState:UIControlStateNormal];
            });
            
        }
    });
    dispatch_resume(_timer);
}


#pragma mark --actions
-(void)skip:(UIButton*)sender{
    [self dismiss];
}

- (void)click:(UITapGestureRecognizer*)tap{
    
    NSURL *url = [NSURL URLWithString:self.advert.url];
    if(url){
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {}];
        } else {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
    
    [[QXAdHandler shareHander] selfAdClickCallBack:self.advert.click_url];
    
    if(self.delegate && [self.delegate respondsToSelector:@selector(QXSplashAdDidClick:)]){
        [self.delegate QXSplashAdDidClick:self];
    }
}


// 移除广告页面
- (void)dismiss{
    if(_timer){
        dispatch_suspend(_timer);
        dispatch_source_cancel(_timer);
    }
    [self removeFromSuperview];
}


- (void)didMoveToSuperview{
    [super didMoveToSuperview];
    if(self.superview){
        
        [self startTimer];

        if(self.delegate && [self.delegate respondsToSelector:@selector(QXSplashAdDidDisplay:)]){
            [self.delegate QXSplashAdDidDisplay:self];
        }
        
        [[QXAdHandler shareHander] selfAdShowCallBack:self.advert.show_url];
    }else{
        
        if(self.delegate && [self.delegate respondsToSelector:@selector(QXSplashAdDidClosed:)]){
            [self.delegate QXSplashAdDidClosed:self];
        }
    }
}


@end
